package servlet;

import pojo.Dept;
import pojo.User;
import service.DeptService;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 此类可以响应web请求
// @ 注解
@WebServlet(urlPatterns = "/user")
public class UserServlet extends HttpServlet {

    // alt + insert


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 3行固定写法
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        // 获取参数
        String username = req.getParameter("username");
        String sex = req.getParameter("sex");
        String str_deptId = req.getParameter("deptId");
        // 将字符串类型的部门编号转换为整数类型
        int deptId = 0;
        if (str_deptId != null) {
            deptId = Integer.parseInt(str_deptId);
        }
        // 判断参数
        User user = new User();
        if (username != null && !"".equals(username)) {
            user.setUsername(username);
        }

        if (sex != null && !"".equals(sex)) {
            user.setSex(sex);
        }

        if (deptId != 0) {
            user.setDeptId(deptId);
        }

        UserService userService = new UserService();
        List<User> userList = userService.getUserList(user);
        int count = userService.count();

        // 查询部门信息
        DeptService deptService = new DeptService();
        List<Dept> deptList = deptService.getAllDeptList();


        // 存下来  session
        req.getSession().setAttribute("userList",userList);
        req.getSession().setAttribute("deptList",deptList);
        req.getSession().setAttribute("count",count);
        // 转发到对应的页面显示数据
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }
}
